<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="合同编号" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入合同编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入客户名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select clearable filterable v-model="queryParams.status" placeholder="请选择状态">
          <el-option v-for="dict in dict.type.CommDataStatus" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['extend:customer:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['extend:customer:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['extend:customer:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['extend:customer:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed/>
      <el-table-column label="合同编号" align="left" prop="code" width="150" />
      <el-table-column label="客户名称" align="left" prop="name" min-width="150" />
      <el-table-column label="合同日期" align="center" prop="startTime" width="200">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
          至
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="距合同结束(天)" align="left" prop="days" width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.days >= 0"> {{ '剩余' + scope.row.days + '天' }}</el-tag>
          <el-tag type="danger" v-else> {{ '已过期' + (-scope.row.days) + '天' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="销售负责人" align="center" prop="salePerson" width="100" />
      <el-table-column label="结算方式" align="center" prop="settlementType" width="150">
        <template #default="scope">
          <dict-tag :options="dict.type.Clearing" :value="scope.row.settlementType" />
          <el-tag style="margin-top: 10px;">账期:{{ scope.row.paymentDays }} 月</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="注册公司" align="left" prop="dtMap.jcRegistrationDtLabel" min-width="100" />
      <el-table-column label="组织机构" align="left" prop="dtMap.jcOrganizationIdDtLabel" min-width="100" />
      <el-table-column label="适用范围" align="left" prop="dtMap.jcOrganizationIdsDtLabel" min-width="100" :show-overflow-tooltip="true" />
      <el-table-column label="行政区域(城市)" align="center" prop="dtMap.jcZoneIdDtLabel" width="120" />
      <el-table-column label="合同文件" align="center" prop="contactFile">
        <template #default="scope">
          <a href="scope.row.contactFile"><i class="el-icon-notebook-2" v-if="scope.row.contactFile"></i></a>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="dict.type.CommDataStatus" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="查看" align="center" prop="status" width="100" fixed="right">
        <template #default="scope">
          <div>
            <router-link :to="'/extend/customerPrice/index/' + scope.row.id" class="link-type">
              <el-button type="primary" size="small">查看价格</el-button>
            </router-link>
          </div>
          <div style="margin-top: 10px;">
            <router-link :to="'/extend/receivingparty/index/' + scope.row.id" class="link-type">
              <el-button type="warning" size="small">查看地址</el-button>
            </router-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="120" fixed="right">
        <template #default="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['extend:customer:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['extend:customer:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改客户管理对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="850px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="合同编号" prop="code">
              <el-input v-model="form.code" placeholder="请输入合同编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同开始日期" prop="startTime">
              <el-date-picker clearable v-model="form.startTime" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择合同开始日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同结束日期" prop="endTime">
              <el-date-picker clearable v-model="form.endTime" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择合同结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账期(月)" prop="paymentDays">
              <el-input-number size="mini" v-model="form.paymentDays" placeholder="请输入账期(月)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售负责人" prop="salePerson">
              <el-input v-model="form.salePerson" placeholder="请输入销售负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结算方式" prop="settlementType">
              <el-select filterable v-model="form.settlementType" placeholder="请选择结算方式">
                <el-option v-for="dict in dict.type.Clearing" :key="dict.value" :label="dict.label"
                  :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册公司" prop="jcRegistration">
              <el-select filterable v-model="form.jcRegistration" placeholder="请选择结算方式">
                <el-option v-for="dict in dict.type.DB_REGISTRATION" :key="dict.value" :label="dict.label"
                  :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="行政区域(城市)" prop="jcZones">
              <el-cascader :props="regionProps" v-model="form.jcZones" style="width: 100%;"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.CommDataStatus" :key="dict.value" :label="parseInt(dict.value)">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组织机构" prop="jcOrganizationId">
              <el-select clearable filterable v-model="form.jcOrganizationId" placeholder="请选择出发网点" disabled="disabled">
                <el-option v-for="dict in dict.type.DB_JC_ORG" :key="dict.value" :label="dict.label"
                  :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="适用范围" prop="jcOrganizationIds">
              <el-select clearable filterable v-model="form.jcOrganizationIdArrays" placeholder="适用网点范围" multiple
                style="width: 95%;" @change="$forceUpdate()">
                <el-option v-for="dict in dict.type.DB_JC_ORG" :key="dict.value" :label="dict.label"
                  :value="dict.value + ''"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="合同文件" prop="contactFile">
              <file-upload v-model="form.contactFile" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addCustomer, delCustomer, getCustomer, listCustomer, updateCustomer } from '@/api/extend/customer'
import { getChildZone } from '@/api/kysys/zone'

export default {
  name: 'Customer',
  dicts: ['CommDataStatus', 'Clearing', 'DB_REGISTRATION', 'DB_JC_ORG'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户管理表格数据
      customerList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        status: null,
        salePerson: null,
        settlementType: null,
        jcRegistration: null,
        jcOrganizationId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          { required: true, message: '合同编号不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '客户名称不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '合同开始日期不能为空', trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: '合同结束日期不能为空', trigger: 'blur' }
        ],
        paymentDays: [
          { required: true, message: '账期(月)不能为空', trigger: 'blur' }
        ],
        salePerson: [
          { required: true, message: '销售负责人不能为空', trigger: 'blur' }
        ],
        settlementType: [
          { required: true, message: '结算方式不能为空', trigger: 'change' }
        ],
        jcRegistration: [
          { required: true, message: '注册公司不能为空', trigger: 'blur' }
        ],
        jcZones: [
          { required: true, message: '行政区域(城市)不能为空', trigger: 'blur' }
        ]
      },
      regionProps: {
        lazy: true,
        lazyLoad(node, resolve) {
          let zid = node.value || 0
          getChildZone({ zid: zid }).then(response => {
            resolve(response.data)
          })
        },
        checkStrictly: true,
        value: 'id',
        label: 'name',
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询客户管理列表 */
    getList() {
      this.loading = true
      listCustomer(this.queryParams).then(response => {
        this.customerList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 转换行政区域数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        createName: null,
        createTime: null,
        description: null,
        modifyName: null,
        modifyTime: null,
        name: null,
        status: 1,
        startTime: null,
        endTime: null,
        paymentDays: null,
        salePerson: null,
        settlementType: null,
        jcRegistration: null,
        jcOrganizationId: null,
        jcZoneId: null,
        contactFile: null,
        jcOrganizationIds: null,
        jcOrganizationIdArrays: []

      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加客户管理'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getCustomer(id).then(response => {
        this.form = response.data
        if (this.form.jcZones) {
          this.form.jcZones = this.form.jcZones.split(',')
        }
        if (this.form.jcOrganizationIds) {
          this.form.jcOrganizationIdArrays = this.form.jcOrganizationIds.split(',')
        }
        this.open = true
        this.title = '修改客户管理'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.jcZones) {
            this.form.jcZoneId = this.form.jcZones[this.form.jcZones.length - 1]
            this.form.jcZones = this.form.jcZones.join(',')
            this.form.jcOrganizationIds = this.form.jcOrganizationIdArrays.join(',')
          }
          if (this.form.id != null) {
            updateCustomer(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addCustomer(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除客户管理编号为"' + ids + '"的数据项？').then(function () {
        return delCustomer(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('extend/customer/export', {
        ...this.queryParams
      }, `customer_${new Date().getTime()}.xlsx`)
    },
    handleRegionChange(value) {
      console.log(value)
    }
  }
}
</script>
